<template>
	<view class="edit">
		<view class="title">
			<input v-model="form.title" type="text" placeholder="请输入标题" placeholder-class="placeholder-class"/>
		</view>
		<view class="content">
			<editor id="editor" @statuschange="onStatusChange" @ready="onEditorReady" @focus="onFocus" placeholder="写点什么吧～" show-img-size show-img-resize show-img-toolbar></editor>
		</view>
		<view class="btns">
			<u-button @click="submit" type="primary" text="确认发表" :disabled="!form.title"></u-button>
		</view>
		<view v-if="showTools" class="tools">
			<view @click="itemClick(item.name,index)" class="item" v-for="(item,index) in tools" :key="index">
				<text class="iconfont" :class="[item.icon,item.active?'active':'']"></text>
			</view>
		</view>
	</view>
</template>

<script>
	import {getImgSrc,getProvince} from '@/utils/tools.js'
	const db = uniCloud.database();
	export default {
		data() {
			return {
				type:"add",// add 发布 edit 编辑
				showTools:false,
				editorCtx:null,
				tools:[
					{name:'header',icon:'icon-biaotizhengwenqiehuan',active:false},
					{name:'bold',icon:'icon-zitijiacu',active:false},
					{name:'italic',icon:'icon-T-qingxie',active:false},
					{name:'insertDivider',icon:'icon-hengxian',active:false},
					{name:'insertImage',icon:'icon-tupian',active:false},
					{name:'confirm',icon:'icon-zhengque',active:false},
				],
				artId:'',
				form:{
					title:'',
					content:'',
					description:'',
					picUrls:'',
					province:''
				},
			};
		},
		onLoad(options) {
			this.type = options.type || 'add';
			uni.setNavigationBarTitle({
				title:options.type=='add'?'发布文章':'编辑文章'
			})
			getProvince().then(res=>{
				this.form.province = res;
			})
			if(options.id){
				this.artId =options.id;
				this.getArtDetail()
			}
		},
		methods:{
			// 获取文章详情
			async getArtDetail(){
				db.collection("circle-articles").doc(this.artId).field(`title,content`).get({
					getOne:true
				}).then(res=>{
					let obj = res.result.data;
					let form = Object.assign({},this.form)
					form.title=obj.title;
					form.content = obj.content;
					this.form = form;
					this.editorCtx.setContents({
						html:this.form.content
					})
				})
			},
			// 初始化
			onEditorReady(){
				uni.createSelectorQuery().in(this).select('#editor').fields({
					size:true,
					context:true
				},res=>{
					this.editorCtx = res.context;
				}).exec();
			},
			// 	聚焦
			onFocus(){
				this.showTools = true;
			},
			// 富文本工具栏点击
			itemClick(name,index){
				if(name!='confirm'){
					this.tools[index].active = !this.tools[index].active;
					switch(name){
						case 'header':
							this.editorCtx.format("header",this.tools[index].active?'H2':false);
						break;
						case 'bold':
							this.editorCtx.format("bold");
						break;
						case 'italic':
							this.editorCtx.format("italic");
						break;
						case 'insertDivider':
							this.tools[index].active = false;
							this.editorCtx.insertDivider();
						break;
						case 'insertImage':
							uni.chooseImage({
								count:9,
								success: async (res) => {
									uni.showLoading({
										title:"上传中，请稍后～",
										mask:true
									})
									for(let item of res.tempFiles){
										let res = await uniCloud.uploadFile({
											filePath:item.path,
											cloudPath:item.name
										})
										this.editorCtx.insertImage({
											src:res.fileID
										})
									}
									uni.hideLoading()
								}
							})
						break;
					}
				}else{
					this.showTools = false;
				}
				
			},
			// 监听富文本样式改变
			onStatusChange(e){
				let detail = e.detail;
				this.tools.forEach(item=>{
					if(detail.hasOwnProperty(item.name)){
						item.active = true
					}else{
						item.active = false
					}
				})
			},
			// 发布
			submit(){
				let content = this.editorCtx.getContents({
					success:res=>{
						this.form.content = res.html;
						this.form.description = res.text.slice(0,80);
						this.form.picUrls = getImgSrc(res.html)
						console.log(this.form)
						if(this.type=='add'){
							this.publishArticle()
						}else{
							this.updateArticle()
						}
					}
				})
			},
			// 发布文章
			publishArticle(){
				uni.showLoading({
					title:"正在发布..."
				})
				db.collection("circle-articles").add(this.form).then(res=>{
					uni.hideLoading();
					uni.showToast({
						title:"发布成功"
					})
					setTimeout(()=>{
						uni.navigateBack()
					},1000)
				})
			},
			// 编辑文章
			updateArticle(){
				uni.showLoading({
					title:"正在发布..."
				})
				db.collection("circle-articles").doc(this.artId).update(this.form).then(res=>{
					uni.hideLoading();
					uni.showToast({
						title:"发布成功"
					})
					setTimeout(()=>{
						uni.navigateBack()
					},1000)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.edit{
		padding: 30rpx;
		.title{
			input{
				font-size: 46rpx;
				height: 120rpx;
				border-bottom: 1px solid #e4e4e4;
				color: #333;
			}
			.placeholder-class{
				color: #e0e0e0;
			}
		}
		.content{
			height: calc(100vh - 500rpx);
			margin: 30rpx 0;
			/deep/ .ql-blank::before{
				font-style: normal;
				color: #e0e0e0;
			}
			#editor{
				width: 100%;
				height: 100% !important;
			}
		}
		.tools{
			background-color: #fff;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
			border-top: 1px solid #f4f4f4;
			position: fixed;
			left:0;
			right: 0;
			bottom: 0;
			.item{
				padding: 10rpx;
			}
			.iconfont{
				font-size: 36rpx;
				color: #333;
				&.active{
					color: #0199FE;
				}
			}
		}
	}

</style>
